﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LunwenYun.Portal.Web.Models;
using LunwenYun.Infrastructure.Entities.Enum;
using LunwenYun.Portal.Biz;
using LunwenYun.Infrastructure.Entities.Entity;
using System.IO;
using LunwenYun.Portal.WebLogic;
using LunwenYun.Tool.Framework;

namespace LunwenYun.Portal.Web.Controllers
{
    /// <summary>
    /// 约稿人
    /// </summary>
    [ErrorHandle]
    [Compress]
    public class oController : SiteBaseController
    {
        [CompleteAgentInfo]
        [Auth(UserRole.PaperAgent)]
        public ActionResult NewPeriodical()
        {
            return View();
        }

        [CompleteAgentInfo]
        [HttpPost]
        [Auth(UserRole.PaperAgent)]
        public ActionResult NewPeriodical(PeriodicalModel model)
        {
            model.Name = model.Name.Trim();
            if (model != null)
            {
                var file = System.Web.HttpContext.Current.Request.Files["CoverImage"];
                if (file != null && file.ContentLength > 0)
                {
                    string basedir = "/content/periodical/" + model.Name + "/coverimage/";
                    if (!System.IO.Directory.Exists(HttpContext.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Server.MapPath(basedir));
                    }
                    var fileinfo = new FileInfo(file.FileName);
                    string filePath = basedir + model.Name + "-converimage" + fileinfo.Extension;
                    file.SaveAs(HttpContext.Server.MapPath(filePath));
                    model.CoverImage = filePath;
                }
                model.Retrieval = String.IsNullOrEmpty(model.Retrieval)?"":model.Retrieval.Replace("\r\n","<br />").NoHTMLLabel("script");
                model.HeXinDescription = String.IsNullOrEmpty(model.HeXinDescription)?"":model.HeXinDescription.Replace("\r\n","<br />").NoHTMLLabel("script");
                model.Honour = String.IsNullOrEmpty(model.Honour)?"":model.Honour.Replace("\r\n","<br />").NoHTMLLabel("script");
                if (SystemBiz.NewPeriodical(
                    HttpContext.User.Identity.Name,
                    new Periodical()
                    {
                        Name = model.Name,
                        Name_EN = model.Name_EN,
                        IndType = (IndType)model.IndType,
                        SubIndType = (SubIndType)model.SubIndType,
                        Introduction = model.Introduction,
                        Aptitude = ";"+ model.Aptitude,
                        Language = (Language)model.Language,
                        PubRate = (PubRate)model.PubRange,
                        ZGDW = model.ZGDW,
                        ZBDW = model.ZBDW,
                        XBDW = model.XBDW,
                        SZ = model.SZ,
                        Editor = model.Editor,
                        ZR = model.ZR,
                        ISSN_Online = model.ISSN,
                        CN_Code = model.CN_No,
                        Price = model.Price,
                        URL = model.Site,
                        Phone = model.Phone,
                        Email = model.Email,
                        Address = model.Address,
                        PostCode = model.PostCode,
                        PostNo = model.PostNo,
                        CoverImg = model.CoverImage,
                        IsActive=false,
                        Retrieval = model.Retrieval,
                        HeXinDescription = model.HeXinDescription,
                        Honour = model.Honour,
                        Creator=HttpContext.User.Identity.Name
                    }) != null)
                {
                    return RedirectToAction("newperiodicalisrecord");
                }
                return RedirectToAction("newperiodicalNotrecord");
            }
            return View();
        }

        [Auth(UserRole.PaperAgent)]
        [CompleteAgentInfo]
        public ActionResult NewPeriodIcalIsRecord()
        {
            return View();
        }

        [Auth(UserRole.PaperAgent)]
        [CompleteAgentInfo]
        public ActionResult NewPeriodIcalNotRecord()
        {
            return View();
        }
        
        public bool PeriodicalIsOnly(string Name)
        {
            var result = SystemBiz.CheckPeriodicalName(Name);
            return result;
        }
        [Auth(UserRole.PaperAgent)]
        public ActionResult AuthorCenter(int page=0)
        {
            List<Article> list = SystemBiz.GetMyAgentPeriodicalManuscript(HttpContext.User.Identity.Name, page, 8);
            ViewBag.Data = new ItemListBox<Article>(list)
                .BuildPage(SystemBiz.GetMyAgentPeriodicalManuscriptForPage(HttpContext.User.Identity.Name), page, 8,
                new PageParameter() { Style = "home" });
            ViewBag.OrderCount = SystemBiz.GetMyNewOrderForPage(HttpContext.User.Identity.Name);
            return View();
        }

        [Auth(UserRole.PaperAgent)]
        public ActionResult ResetPassword()
        {
            ViewBag.OrderCount = SystemBiz.GetMyNewOrderForPage(HttpContext.User.Identity.Name);
            return View();
        }

        [HttpPost]
        [Auth(UserRole.PaperAgent)]
        public ActionResult ResetPassword(string oldPwd, string newPwd)
        {
            if (UserBiz.ChangePassword(HttpContext.User.Identity.Name,
                oldPwd, newPwd) != null)
            {
                ViewBag.Success = true;
                ViewBag.Message = "修改成功";
            }
            else
            {
                ViewBag.Success = false;
                ViewBag.Message = "修改失败，原密码错误";
            } 
            ViewBag.OrderCount = SystemBiz.GetMyNewOrderForPage(HttpContext.User.Identity.Name);
            return View();
        }

        [Auth(UserRole.PaperAgent)]
        public ActionResult profile(string ret)
        {
            ViewBag.OrderCount = SystemBiz.GetMyNewOrderForPage(HttpContext.User.Identity.Name);
            var user = new User().Find(HttpContext.User.Identity.Name);
            ViewBag.User = user;
            var agentInfo = new PaperAgentInfo();
            if (user.IsComplete)
            {
                agentInfo = new PaperAgentInfo().Find(user.UserName);
            }
            else
            {
                agentInfo.Email = user.UserName;
                agentInfo.Name = user.NickName;
            }
            ViewBag.AgentInfo = agentInfo;
            ViewBag.ReturnUrl = ret;
            return View();
        }
        [HttpPost]
        [Auth(UserRole.PaperAgent)]
        [ValidateInput(false)]
        public ActionResult profile(AgentInfoModel model,string ret)
        {
            if (UserBiz.SetAgentInfo(HttpContext.User.Identity.Name, new PaperAgentInfo()
            {
                AccountNo = model.AccountNo,
                AccountType = (AccountType)model.AccountType,
                Declaration = model.Declaration,
                Email = model.Email,
                Introduction = model.Introduction,
                Name = model.Name,
                Phone = model.Phone,
                QQ = model.QQ,
                RcdDate = DateTime.Now,
                RefreshDate = DateTime.Now
            }))
            {
                var user = new User().Find(HttpContext.User.Identity.Name); var agentInfo = new PaperAgentInfo();
                if (user.IsComplete)
                {
                    agentInfo = new PaperAgentInfo().Find(user.UserName);
                }
                else
                {
                    agentInfo.Email = user.UserName;
                    agentInfo.Name = user.NickName;
                }
                ViewBag.AgentInfo = agentInfo;
                ViewBag.User = user;
                ViewBag.Success = true;
                ViewBag.Message = "保存成功";
            }
            else
            {
                var user = new User().Find(HttpContext.User.Identity.Name); var agentInfo = new PaperAgentInfo();
                if (user.IsComplete)
                {
                    agentInfo = new PaperAgentInfo().Find(user.UserName);
                }
                else
                {
                    agentInfo.Email = user.UserName;
                    agentInfo.Name = user.NickName;
                }
                ViewBag.AgentInfo = agentInfo;
                ViewBag.User = user;
                ViewBag.Success = false;
                ViewBag.Message = "保存失败，请稍后重试或联系管理员";
            }
            if (!String.IsNullOrEmpty(ret))
            {
                return Redirect(ret);
            } 
            ViewBag.OrderCount = SystemBiz.GetMyNewOrderForPage(HttpContext.User.Identity.Name);
            return View();
        }

        [Auth(UserRole.PaperAgent)]
        [CompleteAgentInfo]
        public ActionResult editorApply(int id)
        {
            var periodical = new Periodical().Find(id.ToString());
            if (periodical == null)
            {
                return Redirect("/j/index/" + id);
            }
            if (new Agent().Any(c => c.UserName == HttpContext.User.Identity.Name && c.PeriodicalId == id))
            {
                return RedirectToAction("isaditor");
            }
            ViewBag.Periodical = periodical;
            return View();
        }
        [Auth(UserRole.PaperAgent)]
        [CompleteAgentInfo]
        public ActionResult Launch(int id)
        {
            var article = new Article().Find(id.ToString());
            if (article == null)
            {
                return Redirect("/j/article/" + id.ToString());
            }
            ViewBag.Article = article;
            return View();
        }

        /// <summary>
        /// 约稿人向投稿人发起交易
        /// </summary>
        /// <param name="id"></param>
        /// <param name="price"></param>
        /// <param name="introduction"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        [Auth(UserRole.PaperAgent)]
        [CompleteAgentInfo]
        public ActionResult postLaunch(int id, decimal price, string introduction)
        {
            var article = new Article().Find(id.ToString());
            if (article == null)
            {
                return Redirect("/j/article/"+id.ToString());
            }
            ViewBag.Article = article;
            SystemBiz.NewTrading(id, HttpContext.User.Identity.Name, price, introduction.Replace("\r\n", "<br />").NoHTMLLabel("script"));
            return View();
        }

        [HttpPost]
        [Auth(UserRole.PaperAgent)]
        [ValidateInput(false)]
        [CompleteAgentInfo]
        public ActionResult editorApply(int id,string about)
        {
            if (SystemBiz.EditorApply(id, about.Replace("\r\n","<br/>").NoHTMLLabel("script"), HttpContext.User.Identity.Name) != null)
            {
                return RedirectToAction("isapply", new { id = 1 });
            }
            return RedirectToAction("isapply", new { id = 0 });
        }

        [Auth(UserRole.PaperAgent)]
        public ActionResult isaditor()
        {
            return View();
        }

        public ActionResult isapply(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        [Auth(UserRole.PaperAgent)]
        public ActionResult myorders(int page=0)
        {
            ViewBag.OrderCount = SystemBiz.GetMyNewOrderForPage(HttpContext.User.Identity.Name);

            List<Trade> orders = SystemBiz.GetMyAllOrder(HttpContext.User.Identity.Name, page, 10);
            ViewBag.Orders = new ItemListBox<Trade>(orders)
                .BuildPage(SystemBiz.GetMyAllOrderForPage(HttpContext.User.Identity.Name), page, 10,
                new PageParameter() { Style = "home" });
            return View();
        }
        [Auth(UserRole.PaperAgent)]
        public ActionResult industryorders(int page = 0)
        {
            ViewBag.IndustryName = new IndustryCS().Find(HttpContext.User.Identity.Name).Industry;
            ViewBag.OrderCount = SystemBiz.GetMyNewOrderForPage(HttpContext.User.Identity.Name);
            List<Trade> orders = SystemBiz.GetIndustryOrders(HttpContext.User.Identity.Name, page, 10);
            ViewBag.Orders = new ItemListBox<Trade>(orders)
               .BuildPage(SystemBiz.GetIndustryOrderForPage(HttpContext.User.Identity.Name), page, 10,
               new PageParameter() { Style = "home" });
            return View();
        }

        [HttpPost]
        [Auth(UserRole.PaperAgent)]
        public ActionResult industryorderOption(int optionType,decimal price, int id, string token)
        {
            int result = SystemBiz.IndustryOrderOption(optionType, price, id, token);
            if (result == 1)
            {
                return RedirectToAction("industryorders");
            }
            return RedirectToAction("isexpire", new { id = result });
        }
        [HttpPost]
        [Auth(UserRole.PaperAgent)]
        public ActionResult option(int OptionType, int Id, string Token)
        {
            int result = SystemBiz.OrderOption(OptionType, Id, Token);
            if (result == 1)
            {
                return RedirectToAction("myorders");
            }
            return RedirectToAction("isexpire", new { id = result});
        }
        public ActionResult isexpire(int id)
        {
            ViewBag.Id = id;
            return View();
        }
    }
}
